package main

import (
	_ "embed"
	"errors"
	"fmt"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"github.com/zh-five/xexpect/xexpect"
	"github.com/zh-five/xtool/crypto/xaes"
)

//go:embed icon.png
var iconData []byte

// go build -ldflags -H=windowsgui .
func main() {
	//Encrypt()
	showBox()
}

func showBox() {
	// 创建一个新的应用
	myApp := app.New()
	// 创建一个新的窗口
	myWindow := myApp.NewWindow("auto ssh-add")
	myWindow.Resize(fyne.NewSize(300, 200))

	// 创建资源
	icon := fyne.NewStaticResource("appicon.png", iconData)

	// 设置窗口图标
	myWindow.SetIcon(icon)

	label := widget.NewLabel("Please enter your password")
	passwordEntry := widget.NewPasswordEntry()
	passwordEntry.SetPlaceHolder("password")

	// 提交处理
	submit := func() {
		if err := sshAdd(passwordEntry.Text); err != nil {
			label.SetText(err.Error())
		} else {
			myWindow.Close()
		}
	}
	passwordEntry.OnSubmitted = func(string) {
		submit()
	}
	loginButton := widget.NewButton("login", submit)

	// 使用VBox布局管理器组合widgets
	content := container.NewVBox(
		label,
		passwordEntry,
		loginButton,
	)

	// 设置窗口的内容为我们组合的widgets
	myWindow.SetContent(content)

	time.AfterFunc(time.Second, func() {
		// 确保用户名的文本框在窗口显示后获得焦点
		myWindow.Canvas().Focus(passwordEntry)
	})

	// 显示并运行窗口
	myWindow.ShowAndRun()
}

func sshAdd(password string) error {
	sshKey, err := getSshKey(password)
	if err != nil {
		return err
	}

	xe := xexpect.NewXExpect()
	xe.Run([]string{"powershell", "ssh-add", `C:\Users\Administrator\.ssh\id_ed25519`})
	xe.Matchs([][]string{
		{"id_ed25519:", sshKey + "\n", "C"},
		{"Identity added:", ""},
	})
	xe.Exit()
	return nil
}

// 解密ssh 密钥的密码
func getSshKey(password string) (sshKey string, err error) {
	cip := []byte{0xa4, 0x4d, 0xb, 0x96, 0x5e, 0xe, 0x89, 0xd, 0xa6, 0xd4, 0xac, 0x24, 0x80, 0x96, 0x89, 0xb, 0xf6,
		0x6a, 0x8f, 0x73, 0x6c, 0xc6, 0xe, 0xf, 0xfb, 0xbd, 0x3a, 0xfa, 0xd2, 0xd3, 0x1f, 0xa5, 0x65, 0x25, 0xf,
		0x63, 0x78, 0xe9, 0xe4, 0x5f, 0x5, 0x67, 0x29, 0xfd, 0x95, 0xdb, 0xa3, 0xa1, 0xfe, 0x6a, 0xd1, 0x29, 0xe9,
		0xc4, 0xbf, 0x5f, 0x9b, 0xb6, 0x6e, 0x9, 0xb5, 0x6d, 0xf2, 0x69}
	sale := "23hg4w5hhw45h"
	key := password + sale

	xa := xaes.NewAES()
	b, err := xa.Decrypt([]byte(key), cip)
	if err != nil {
		return
	}
	n := len(password)
	if len(b) < n || password != string(b[:n]) {
		err = errors.New("password error")
		return
	}

	sshKey = string(b[n:])
	return
}

func Encrypt() {
	sshKey := "12133" // ssh key 长密码
	key := "124345"   // 加密短密码
	sale := "23hg4w5hhw45h"

	sshKey = key + sshKey
	key += sale

	xa := xaes.NewAES()

	// 加密
	b, err := xa.Encrypt([]byte(key), []byte(sshKey))
	if err != nil {
		panic(err)
	}
	fmt.Printf("out: %#v\n", b)
}
